package com.sneaker.shower.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sneaker.shower.common.BizException;
import com.sneaker.shower.common.ThreadLocalCache;
import com.sneaker.shower.entity.domain.organization.MainImageDO;
import com.sneaker.shower.entity.dto.MainImageDTO;
import com.sneaker.shower.mapper.MainImageMapper;
import com.sneaker.shower.mapstruct.MainImageMapStruct;
import com.sneaker.shower.service.MainImageService;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author Hechangjian
 * @version 1.0
 * @className MainImageServiceImpl
 * @date 2019/08/13 17:44
 * @description
 * @program bath
 */
@Service
public class MainImageServiceImpl extends ServiceImpl<MainImageMapper, MainImageDO> implements MainImageService {

    @Override
    public List<String> getMainImages() {
        String orgGuid = ThreadLocalCache.get().getOrganizationGuid();
        if (orgGuid == null) {
            throw new BizException("当前线程没有orgGuid");
        }
        return this.list(new LambdaQueryWrapper<MainImageDO>()
                .eq(MainImageDO::getOrganizationGuid, Long.parseLong(orgGuid))
                .orderByAsc(MainImageDO::getSort))
                .stream().map(MainImageDO::getUrl)
                .collect(Collectors.toList());
    }

    @Override
    public Boolean saveOrUpdateMainImages(List<MainImageDTO> mainImageDTOS) {
        if (CollectionUtils.isEmpty(mainImageDTOS)) {
            throw new BizException("参数为空");
        }
        List<MainImageDO> mainImageDOS = MainImageMapStruct.INSTANCE.dtoList2DOList(mainImageDTOS);

        int sort = 0;
        for (MainImageDO o : mainImageDOS) {
            o.setGuid(Optional.ofNullable(o.getGuid()).orElse(IdWorker.getId()));
            o.setSort(sort);
            sort++;
        }
        return this.saveOrUpdateBatch(mainImageDOS);
    }

    @Override
    public List<MainImageDTO> getOrgImages(String orgGuid) {
        if (StringUtils.isEmpty(orgGuid)) {
            throw new BizException("门店GUID不能为空");
        }
        return MainImageMapStruct.INSTANCE.doList2DTOList(
                this.list(new LambdaQueryWrapper<MainImageDO>()
                        .eq(MainImageDO::getOrganizationGuid, Long.parseLong(orgGuid))
                        .orderByAsc(MainImageDO::getSort)
                )
        );
    }
}
